<template>
  <div class="school-applications">
    <h2 class="section-title">社团申请管理</h2>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="创建申请" name="create">
        <div class="applications-container">
          <div v-if="createApplications.length === 0" class="no-data">
            <i class="el-icon-inbox"></i>
            <p>暂无社团创建申请</p>
          </div>

          <el-table
            v-else
            :data="createApplications"
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="clubname" label="社团名称" min-width="150"></el-table-column>
            <el-table-column prop="clubType" label="社团类型" width="120"></el-table-column>
            <el-table-column prop="applicantUsername" label="申请人" width="120"></el-table-column>
            <el-table-column prop="applyTime" label="申请时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.applyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 'pending'"
                  size="small"
                  type="success"
                  @click="approveCreateApplication(scope.row)"
                >批准</el-button>
                <el-button
                  v-if="scope.row.status === 'pending'"
                  size="small"
                  type="danger"
                  @click="rejectCreateApplication(scope.row)"
                >拒绝</el-button>
                <el-button
                  size="small"
                  type="info"
                  @click="viewCreateApplicationDetail(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane label="解散申请" name="dissolve">
        <div class="applications-container">
          <div v-if="dissolveApplications.length === 0" class="no-data">
            <i class="el-icon-delete"></i>
            <p>暂无社团解散申请</p>
          </div>

          <el-table
            v-else
            :data="dissolveApplications"
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="clubName" label="社团名称" min-width="150"></el-table-column>
            <el-table-column prop="reason" label="解散原因" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="applyUsername" label="申请人" width="120"></el-table-column>
            <el-table-column prop="applyTime" label="申请时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.applyTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 'pending'"
                  size="small"
                  type="success"
                  @click="approveDissolveApplication(scope.row)"
                >批准</el-button>
                <el-button
                  v-if="scope.row.status === 'pending'"
                  size="small"
                  type="danger"
                  @click="rejectDissolveApplication(scope.row)"
                >拒绝</el-button>
                <el-button
                  size="small"
                  type="info"
                  @click="viewDissolveApplicationDetail(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 申请详情对话框 -->
    <el-dialog
      :title="activeTab === 'create' ? '创建申请详情' : '解散申请详情'"
      v-model="detailDialogVisible"
      width="600px"
    >
      <div v-if="selectedApplication" class="application-detail">
        <div v-if="activeTab === 'create'">
          <div class="detail-item">
            <div class="detail-label">社团Logo</div>
            <div class="detail-value">
                 <img :src="selectedApplication.logo ? `http://localhost:5000/uploads/${selectedApplication.logo}` : ''" alt="Logo" class="detail-logo">
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">社团名称</div>
            <div class="detail-value">{{ selectedApplication.clubname }}</div>
          </div>
           <div class="detail-item">
            <div class="detail-label">社团类型</div>
            <div class="detail-value">{{ selectedApplication.clubType }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">社团简介</div>
            <div class="detail-value text-wrap">{{ selectedApplication.description }}</div>
          </div>
           <div class="detail-item">
            <div class="detail-label">申请理由</div>
            <div class="detail-value text-wrap">{{ selectedApplication.reason }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">申请人</div>
            <div class="detail-value">{{ selectedApplication.applicantUsername }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">申请时间</div>
            <div class="detail-value">{{ formatDate(selectedApplication.applyTime) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">状态</div>
            <div class="detail-value">
                 <el-tag :type="getStatusType(selectedApplication.status)">{{ getStatusText(selectedApplication.status) }}</el-tag>
            </div>
          </div>
          <div class="detail-item" v-if="selectedApplication.status === 'rejected'">
            <div class="detail-label">拒绝理由</div>
            <div class="detail-value text-wrap">{{ selectedApplication.rejectReason }}</div>
          </div>
        </div>

        <div v-else>
          <div class="detail-item">
            <div class="detail-label">社团名称</div>
            <div class="detail-value">{{ selectedApplication.clubName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">解散原因</div>
            <div class="detail-value text-wrap">{{ selectedApplication.reason }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">申请人</div>
            <div class="detail-value">{{ selectedApplication.applyUsername }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">申请时间</div>
            <div class="detail-value">{{ formatDate(selectedApplication.applyTime) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">当前成员数</div>
            <div class="detail-value">{{ selectedApplication.memberCount || 0 }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">状态</div>
            <div class="detail-value">
                 <el-tag :type="getStatusType(selectedApplication.status)">{{ getStatusText(selectedApplication.status) }}</el-tag>
            </div>
          </div>
           <div class="detail-item" v-if="selectedApplication.status === 'rejected'">
            <div class="detail-label">拒绝理由</div>
            <div class="detail-value text-wrap">{{ selectedApplication.rejectReason }}</div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="selectedApplication && selectedApplication.status === 'pending'"
            type="success"
            @click="approveApplication(selectedApplication)"
          >批准</el-button>
          <el-button
            v-if="selectedApplication && selectedApplication.status === 'pending'"
            type="danger"
            @click="rejectApplication(selectedApplication)"
          >拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  schoolId: {
    type: String,
    required: true
  }
})

// 页面状态
const activeTab = ref('create')
const loading = ref(false)
const createApplications = ref([])
const dissolveApplications = ref([])
const detailDialogVisible = ref(false)
const selectedApplication = ref(null)

// 监听schoolId变化，重新加载数据
watch(() => props.schoolId, (newValue) => {
  if (newValue) {
    fetchApplications()
  }
})

// 监听标签页变化，重新获取对应的数据
watch(() => activeTab.value, () => {
  fetchApplications()
})

// 获取申请数据
const fetchApplications = async () => {
  if (!props.schoolId) return

  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
        ElMessage.warning('请先登录以查看申请');
        loading.value = false;
        return;
    }

    if (activeTab.value === 'create') {
      // 获取创建申请 (调用新的 API)
      const response = await axios.get(`http://localhost:5000/schools/${props.schoolId}/club-applications`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      createApplications.value = response.data || []
    } else {
      // 获取解散申请 (假设 API 路径，后续可能需要调整)
      // TODO: 实现获取解散申请的后端 API
      console.warn('获取社团解散申请的功能尚未完全实现');
      const response = await axios.get(`http://localhost:5000/schools/${props.schoolId}/club-dissolution-applications`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      dissolveApplications.value = response.data || []
    }
  } catch (error) {
    console.error('获取申请数据失败:', error)
    ElMessage.error('获取申请数据失败: ' + (error.response?.data?.message || error.message))
    // 清空数据以避免显示旧数据
    if (activeTab.value === 'create') {
      createApplications.value = []
    } else {
      dissolveApplications.value = []
    }
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'approved': return 'success'
    case 'rejected': return 'danger'
    default: return 'warning' // pending
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'approved': return '已批准'
    case 'rejected': return '已拒绝'
    default: return '待审核' // pending
  }
}

// 查看创建申请详情
const viewCreateApplicationDetail = (application) => {
  selectedApplication.value = application
  detailDialogVisible.value = true
}

// 查看解散申请详情
const viewDissolveApplicationDetail = async (application) => {
  selectedApplication.value = application;
  try {
    const memberResponse = await axios.get(`http://localhost:5000/clubs/${application.clubId}/members`);
    selectedApplication.value.memberCount = memberResponse.data?.length || 0;
  } catch (error) {
      if (error.response?.status === 404) {
          console.log("社团可能已被解散，无法获取成员数");
          selectedApplication.value.memberCount = 0; // 或显示 "已解散"
      } else {
          console.error('获取社团成员数失败:', error);
          selectedApplication.value.memberCount = '未知';
      }
  }
  detailDialogVisible.value = true;
}

// 批准创建申请
const approveCreateApplication = async (application) => {
  try {
    await ElMessageBox.confirm(
      `确认批准创建社团 "${application.clubname}" 吗？`,
      '批准申请',
      {
        confirmButtonText: '确认批准',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const token = localStorage.getItem('token')
    if (!token) {
        ElMessage.warning('请先登录');
        return;
    }
    // 调用新的批准 API
    await axios.put(
      `http://localhost:5000/schools/${props.schoolId}/club-applications/${application._id}/approve`,
      {},
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )

    ElMessage.success('已批准社团创建申请')
    fetchApplications() // 刷新数据
  } catch (error) {
    if (error === 'cancel') return
    console.error('批准创建申请失败:', error)
    ElMessage.error('批准创建申请失败: ' + (error.response?.data?.message || error.message))
  }
}

// 拒绝创建申请
const rejectCreateApplication = async (application) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入拒绝原因',
      '拒绝申请',
      {
        confirmButtonText: '确认拒绝',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝原因',
        inputValidator: (value) => {
            if (!value || value.trim().length === 0) {
                return '拒绝原因不能为空';
            }
            return true;
        }
      }
    )

    const token = localStorage.getItem('token')
     if (!token) {
        ElMessage.warning('请先登录');
        return;
    }
    // 调用新的拒绝 API
    await axios.put(
      `http://localhost:5000/schools/${props.schoolId}/club-applications/${application._id}/reject`,
      { reason }, // 将理由放在请求体中
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )

    ElMessage.success('已拒绝社团创建申请')
    fetchApplications() // 刷新数据
  } catch (error) {
    if (error === 'cancel' || !error?.value) { // 检查是否是取消操作或没有输入值
         console.log('用户取消或未输入拒绝理由');
         return; // 不显示错误提示
     }
    console.error('拒绝创建申请失败:', error)
    ElMessage.error('拒绝创建申请失败: ' + (error.response?.data?.message || error.message))
  }
}

// 批准解散申请
const approveDissolveApplication = async (application) => {
    try {
      await ElMessageBox.confirm(
        `确认批准解散社团 "${application.clubName}" 吗？此操作将永久删除该社团及其相关数据，请谨慎操作！`,
        '批准解散',
        {
          confirmButtonText: '确认解散',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      const token = localStorage.getItem('token')
      if (!token) {
          ElMessage.warning('请先登录');
          return;
      }
      await axios.put(
        `http://localhost:5000/schools/${props.schoolId}/club-dissolution-applications/${application._id}/approve`,
        {},
        {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }
      )

      ElMessage.success('已批准社团解散申请，社团已解散')
      fetchApplications() // 刷新数据
    } catch (error) {
      if (error === 'cancel') return

      console.error('批准解散申请失败:', error)
      ElMessage.error('批准解散申请失败: ' + (error.response?.data?.message || error.message))
    }
}

// 拒绝解散申请
const rejectDissolveApplication = async (application) => {
    try {
      const { value: reason } = await ElMessageBox.prompt(
        '请输入拒绝解散的原因',
        '拒绝解散',
        {
          confirmButtonText: '确认拒绝',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入拒绝原因',
          inputValidator: (value) => {
               if (!value || value.trim().length === 0) {
                  return '拒绝原因不能为空';
              }
              return true;
          }
        }
      )

      const token = localStorage.getItem('token')
      if (!token) {
          ElMessage.warning('请先登录');
          return;
      }
      await axios.put(
        `http://localhost:5000/schools/${props.schoolId}/club-dissolution-applications/${application._id}/reject`,
        { reason },
        {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }
      )

      ElMessage.success('已拒绝社团解散申请')
      fetchApplications() // 刷新数据
    } catch (error) {
      if (error === 'cancel' || !error?.value) {
           console.log('用户取消或未输入拒绝理由');
           return; // 不显示错误提示
       }
      console.error('拒绝解散申请失败:', error)
      ElMessage.error('拒绝解散申请失败: ' + (error.response?.data?.message || error.message))
    }
}

// 从详情对话框批准申请
const approveApplication = (application) => {
  if (activeTab.value === 'create') {
    approveCreateApplication(application)
  } else {
    approveDissolveApplication(application)
  }
  detailDialogVisible.value = false
}

// 从详情对话框拒绝申请
const rejectApplication = (application) => {
  if (activeTab.value === 'create') {
    rejectCreateApplication(application)
  } else {
    rejectDissolveApplication(application)
  }
  detailDialogVisible.value = false
}

// 组件挂载时获取申请数据
onMounted(() => {
  if (props.schoolId) {
    fetchApplications()
  }
})
</script>

<style scoped>
.school-applications {
  padding: 20px 0;
}

.section-title {
  color: #fff;
  font-size: 24px;
  margin-bottom: 30px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.applications-container {
  margin-top: 20px;
}

.no-data {
  padding: 40px;
  text-align: center;
  color: #666;
  background-color: #1f1b24;
  border-radius: 10px;
  margin: 20px 0;
}

.no-data i {
  font-size: 40px;
  margin-bottom: 15px;
  display: block;
}

/* 详情对话框样式 */
.application-detail {
  padding: 15px;
  background-color: #1f1b24;
  border-radius: 8px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-label {
  width: 120px;
  color: #b0bec5;
  font-weight: bold;
  flex-shrink: 0; /* 防止标签被压缩 */
}

.detail-value {
  flex: 1;
  color: #eee;
}

.text-wrap {
    white-space: pre-wrap; /* 保留换行和空格 */
    word-break: break-all; /* 允许在单词内换行 */
}

.detail-logo {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 6px;
    border: 1px solid #444;
}

/* Element Plus 组件样式重写 */
:deep(.el-tabs__item) {
  color: #b0bec5;
}

:deep(.el-tabs__item.is-active) {
  color: #00aeff;
}

:deep(.el-tabs__active-bar) {
  background-color: #00aeff;
}

:deep(.el-table) {
  background-color: transparent;
  color: #eee;
}

:deep(.el-table th) {
  background-color: #1f1b24;
  color: #b0bec5;
  border-bottom-color: #333;
}

:deep(.el-table tr) {
  background-color: #28232e;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #23202a;
}

:deep(.el-table td) {
  border-bottom-color: #333;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #342e3d;
}

:deep(.el-dialog) {
  background-color: #28232e;
  border-radius: 10px;
}

:deep(.el-dialog__title) {
  color: #fff;
}

:deep(.el-dialog__body) {
  color: #b0bec5;
}

:deep(.el-button) {
  margin-left: 5px;
}
</style>
